import { getPayCategories, createExpense } from '../../../api/expense'
const util = require('../../../utils/util.js')
import { isEmpty } from '../../../utils/validator'
var app = getApp()

var toptip // 保存toptip组件的引用
Page({
  data: {
    pay_type_tab: [
      { k: 'spending', v: '支出' }, { k: 'income', v: '收入' }, { k: 'transfer', v: '转帐' }
    ],
    scrollLeft: 0,
    categories: [],
    // 支付方式
    pay_way_array: ['微信', '支付宝', '银行卡', '现金'],
    pay_way_object: [{ k: 'wechat', v: '微信' }, { k: 'alipay', v: '支付宝' }, { k: 'bankcard', v: '银行卡' }, { k: 'cash', v: '现金' }],
    pay_way_index: 0,

    query: {
      _paginator: 'none'
    },
    expense: {
      note: '',
      addr: '',
      category: null,
      pay_way: 'wechat',
      pay_type: 'spending',
      pay_date: '',
      pay_time: '',
      amount: null
    }
  },
  onLoad(e) {
    const now = util.formatTime(new Date()).split(' ')
    this.setData({
      [`expense.pay_date`]: now[0],
      [`expense.pay_time`]: now[1]
    })
    getPayCategories(this.data.query).then(res => {
      this.setData({
        categories: res.data
      })
    })
  },
  onReady: function () {
    toptip = this.selectComponent('#toptip')
  },
  // 提交
  submitTap() {
    var expense = this.data.expense
    if (expense.amount === null) {
      return toptip.show('请输入金额')
    }
    if (expense.category === null) {
      return toptip.show('请选择消费类型')
    }
    // expense.pay_time = `${expense.pay_time[0]} ${expense.pay_time[1]}`

    createExpense(expense).then(res => {
      wx.redirectTo({
        url: '../expense?from=add'
      })
    })

  },
  // 备注、金额
  formInputBlur(e) {
    var field = e.currentTarget.dataset.field
    var value = e.detail.value
    this.setData({
      [`expense.` + field]: value
    })
  },
  addrInputBlur(e){
    this.setData({
      [`expense.addr.name`]: e.detail.value
    })
  },
  // 支付类型
  payTypeSelect(e) {
    this.setData({
      scrollLeft: (e.currentTarget.dataset.k - 1) * 60,
      [`expense.pay_type`]: e.currentTarget.dataset.k,
    })
  },
  // 类型分类
  choosePayTap(e) {
    const { color, id } = e.currentTarget.dataset
    this.setData({
      [`expense.category`]: id,
      select_category_border: `border: 0.1em solid ${color};`
    })
  },

  // 消费地址
  chooseLocation() {
    const that = this
    wx.chooseLocation({
      success(res) {
        delete res['errMsg']
        that.setData({
          [`expense.addr`]: res
        })
      }
    })
  },
  // 支付方式
  PayWayChange: function (e) {
    console.log(e)
    this.setData({
      [`expense.pay_way`]: this.data.pay_way_object[e.detail.value].k,
      PayWayChange: e.detail.value
    })
  },
  // 日期时间
  DateChange: function (e) {
    this.setData({
      [`expense.pay_date`]: e.detail.value
    })
  },
  TimeChange: function (e) {
    this.setData({
      [`expense.pay_time`]: e.detail.value
    })
  },

})